<?php
/**
* This form must use $this->services to
* 1. change the Service ID to a dropdown, using the key in the services array
* 2. generate the key - value pair of textboxes for each param in the service user chooses
* 3. Fix the Add / Remove links in each row of key - value textbox. 
* For now, only the first Add / Remove work because the other is not bound with JS
*/
//Get front-end URL
$frontEndUrl='http://'.str_replace('.admin.','.',parse_url(yii::app()->request->getHostInfo(), PHP_URL_HOST));
//Fix in  case domain has "admin" in first position like  "admin.geny.me"
$frontEndUrl='http://'.str_replace('admin.','',parse_url(yii::app()->request->getHostInfo(), PHP_URL_HOST));
?>

<?php 
cs()->registerCssFile('/sites/1/kodo/kodostudios/themes/kodo-cms/styles/form.css');
cs()->registerScript(__CLASS__.'ChooseService', "
var params = ".CJavaScript::encode($this->services).";
$('#SID').change(function(){
    cleanUp();

    $('.param:not(:first)').remove();
    $('.param input').val('');

    if (params[$(this).val()] != undefined)
    {
        if ($(params[$(this).val()]).length)
        {
            $.each(params[$(this).val()], function(key,value){
                var new_param = $('.param:last').clone();
                new_param.find('input:eq(0)').val(key).end()
                    .find('input:eq(1)').val(value);
                $('.param:last').before(new_param);
            });
            $('.param:last').remove();
        }
//        else
//        {
//            $('.param:not(:first)').remove();
//            $('.param input').val('');
//        }
    }
});
");
?>
<div class="form">
    <!--<form action="" method="post">-->
    <?php echo CHtml::beginForm("")?>
    <div class="row">
        <label>Token</label>
        <input name="ApiSec[token]" size="50" value="<?php echo Yii::app()->session->get(ApiSec::TOKEN_KEY_IN_SESSION) ?>" />
    </div>
    <div class="row">
        <label>Service ID</label>
        <?php echo CHtml::dropDownList('SID', 'Core.WebApi.getToken', array_combine(array_keys($this->services),array_keys($this->services)));?>
    </div>
    <div class="row">
        <label>Params</label>
    </div>
    <div class="row param">
        <input name="key">
        <input name="value" size="80">
        <input type="hidden" name="param">
        <a href="#" class="add">Add</a>
        <a href="#" class="remove">Remove</a>
    </div>
    <input type="hidden" name="ApiSec[t]"> 
    <input type="hidden" name="ApiSec[hash]"> 
    <div class="row">
        <input type="submit" value="Submit">
        <input type="button" value="Cleanup" onclick="cleanUp()">
    </div>
</form>
</div>

<iframe id="result-window" width="100%" height="500px" src="/index.php?r=testApi/blank"></iframe>

<script>
function cleanUp(){
    window.frames[0].location = '<?php echo url('/testApi/blank') ?>';
}
//var prepared = false;
$('form').submit(function(){
    if (1){
        if (window.frames[0].document.forms == undefined){
            alert('Clean up first.'); return false;
        };
        date = new Date();
        $('input[name="ApiSec[t]"]').val(Math.floor(date.getTime()/1000));

        $.ajax({
            url: '<?php echo url('/testApi/prepare') ?>',
            data: {
                token: $('input[name="ApiSec[token]"]').val(),
                t: $('input[name="ApiSec[t]"]').val(),
            },
            success: function(data){
//                prepared = true;
                eval('data='+data); 
                // set hash and t params
                $('input[name="ApiSec[hash]"]').val(data.hash);
                
                form =window.frames[0].document.forms[0];
                
                $('form input').each(function(){
                    if ($(this).parent().hasClass('param')) return;
                    $(form).append($(this).clone());
                });

                // build other params
                $('div.param').each(function(){
                    name = $(this).find('input[name="key"]').val(); //$(this).find('input[name="key"]').remove();
                    value = $(this).find('input[name="value"]').val(); //$(this).find('input[name="value"]').remove();
                    $(form).append('<input name="'+name+'" value="'+value+'"/>');
//                    param = $(this).find('input[name=param]');
//                    param.val(value);
//                    param.attr('name',name);
                })
                
                form.action = '<?php echo $frontEndUrl;?>/index.php?r=Core/service/index&FORMAT=xml&SID='+$('#SID').val();
                
                if ($('#SID').val() == 'Core.WebApi.getToken')
                    $(form.document).ready(setTimeout('window.location = location', 3000));
                form.submit();
//                else {
//                    $('form').attr('action',form.action).get(0).submit();
//                }
            },
            asyns: true,
            type: 'post'
        })
    }
    return false;
})

$(document).ready(function(){
    $('.form').delegate('a.add', 'click', function(){
        parent = $(this).parent();
        parent.after(parent.clone());
    })
    $('.form').delegate('a.remove', 'click', function(){
        $(this).parent().remove();
    })
})
</script>